<?php
/*
 *author:Yangligao
 *Date:2013-10-2
 */
require 'Config.php';
$flag = $_GET['flag'];
if($flag == 'addtocar'){
	$food_id = isset($_POST['food_id'])?$_POST['food_id']:'';
	$food_num = isset($_POST['food_num'])?$_POST['food_num']:'';

	$arrOld = array();
	//如果COOKIE[''myproduct]存在需要保留里面的值
	if(isset($_COOKIE['myproduct'])){
		if(!empty($_COOKIE['myproduct'])){
			$arrOld = unserialize($_COOKIE['myproduct']);
		}
	}
	if(!empty($food_id) && !empty($food_num)){
		
		$arrOld["$food_id"] = $food_num;
		$res = setcookie('myproduct',serialize($arrOld),time()+3600*24,'/');
		if($res){
			alertInfo("已成功加入购物车！", $_SERVER['HTTP_REFERER']);
		}else{
			alertInfo('加入购物车失败！', $_SERVER['HTTP_REFERER']);
		}	
	}
}else if($flag == 'changenum'){
	
	$food_id = isset($_GET['food_id'])?$_GET['food_id']:'';
	$food_num = isset($_GET['food_num'])?$_GET['food_num']:'';

	$arrOld = array();
	//如果COOKIE[''myproduct]存在需要保留里面的值
	if(isset($_COOKIE['myproduct'])){
		if(!empty($_COOKIE['myproduct'])){
			$arrOld = unserialize($_COOKIE['myproduct']);
		}
	}
	if(!empty($food_id) && !empty($food_num)){
	
		$arrOld["$food_id"] = $food_num;
		$res = setcookie('myproduct',serialize($arrOld),time()+3600*24,'/');
		if($res){
		$totalPrice=0;
		foreach($arrOld as $key=>$value){
			//通过$key的值获取产品信息
			$foodModel = new FoodModel();
			$res = $foodModel->food_select('food_id,food_name,food_pic,food_singleprice,food_userprice',"where food_id={$key}");
			$res[0]['food_num'] = $value ;//在返回的数组中追加一个购买数量
			$tArr[] = $res[0];
			if(isset($_SESSION['user_name'])){
				$totalPrice = $totalPrice + $res[0]['food_num']*$res[0]['food_userprice'];
			}else{
				$totalPrice = $totalPrice + $res[0]['food_num']*$res[0]['food_singleprice'];
			}
			echo $totalPrice;
		}
		}else{
			echo 0;
		}
	}
	}else if($flag == 'Daddtocar'){
		$food_id = isset($_GET['food_id'])?$_GET['food_id']:'';
		$food_num =1;
		
		$arrOld = array();
		//如果COOKIE[''myproduct]存在需要保留里面的值
		if(isset($_COOKIE['myproduct'])){
			if(!empty($_COOKIE['myproduct'])){
				$arrOld = unserialize($_COOKIE['myproduct']);
			}
		}
		if(!empty($food_id)){
		
			$arrOld["$food_id"] = $food_num;
			$res = setcookie('myproduct',serialize($arrOld),time()+3600*24,'/');
			if($res){
				alertInfo("已成功加入购物车！", $_SERVER['HTTP_REFERER']);
			}else{
				alertInfo('加入购物车失败！', $_SERVER['HTTP_REFERER']);
			}
		}
	}else if($flag == 'deletfromcar'){
		$food_id = $_GET['food_id'];
		
		$arrOld = unserialize($_COOKIE['myproduct']);
		
		if(array_key_exists($food_id, $arrOld)){
			
			unset($arrOld["$food_id"]);
			$res = setcookie('myproduct',serialize($arrOld),time()+3600*24,'/');
			header("Location:".$_SERVER['HTTP_REFERER']);
			
		}
		
		
	}

?>
